<template>
  <div>
    <ElSubmenu v-if="item.children" popper-append-to-body :index="getIndex(item)">
      <template #title>
        <i class="menu-icon" :class="item.icon"></i>
        <div class="menu-title">
          <div class="ellipsis-1" :title="item.title">{{ item.title }}</div>
        </div>
      </template>
      <template v-for="child in item.children">
        <SubmenuRender :key="child.id" :item="child" />
      </template>
    </ElSubmenu>
    <ElMenuItem v-else :key="item.id" :index="getIndex(item)" @click="open(item)">
      <template v-if="!collapse" #default>
        <i class="menu-icon" :class="item.icon"></i>
        <div class="menu-title">
          <div class="ellipsis-1" :title="item.title">{{ item.title }}</div>
        </div>
      </template>
      <template v-if="collapse">
        <i class="menu-icon" :class="item.icon"></i>
        <span class="menu-title">{{ item.title }}</span>
      </template>
    </ElMenuItem>
  </div>
</template>

<script>
  import { getIndex } from './index'
  import { mapState } from 'vuex'
  import { isIframeRoute } from '@/util/iframe'
  import { MenuItem, Submenu } from 'element-ui'
  import { isURL } from '@/util/validate'

  export default {
    name: 'SubmenuRender',
    components: {
      ElSubmenu: Submenu,
      ElMenuItem: MenuItem
    },
    props: {
      item: {
        type: Object,
        default: () => ({})
      }
    },
    computed: {
      ...mapState('viewState', ['collapse'])
    },
    methods: {
      getIndex,
      async open(item) {
        // 在浏览器新标签打开
        if (isURL(item.path)) {
          window.open(item.path, '_blank')
        } else if (isIframeRoute(item.path)) {
          await this.$router.push({ path: item.path, query: { tabTitle: item.title, icon: item.icon } })
        } else {
          await this.$router.push({ path: item.path })
        }
      }
    }
  }
</script>
